<template>
  <view class="product-list-page">
    <!-- 搜索框 -->
    <view class="search-bar flex p-2.5 bg-white sticky top-0 z-10">
      <view class="search-input flex-1 flex items-center bg-light-gray rounded-full px-3 py-1.5">
        <text class="fa fa-search text-gray-400 mr-2"></text>
        <input type="text" v-model="searchKeyword" placeholder="搜索商品" class="flex-1 bg-transparent text-sm" />
      </view>
    </view>

    <!-- 分类选项卡 -->
    <scroll-view scroll-x class="category-tabs whitespace-nowrap bg-white py-2 px-1 border-b border-gray-100">
      <view v-for="(category, index) in categories" :key="index" :class="['category-tab inline-block px-3 py-1 mx-1 rounded-full text-sm',
          currentCategory === index ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600']"
        @tap="selectCategory(index)">
        {{ category.name }}
      </view>
    </scroll-view>

    <!-- 筛选栏 -->
    <view class="filter-bar flex bg-white py-2.5 px-4 text-sm border-b border-gray-100">
      <view class="filter-item flex-1 flex justify-center items-center"
        :class="{ 'text-primary': sortBy === 'default' }" @tap="setSortBy('default')">
        综合 <text class="fa fa-sort ml-1"
          :class="{ 'text-primary': sortBy === 'default', 'text-gray-300': sortBy !== 'default' }"></text>
      </view>
      <view class="filter-item flex-1 flex justify-center items-center" :class="{ 'text-primary': sortBy === 'sales' }"
        @tap="setSortBy('sales')">
        销量 <text class="fa fa-sort ml-1"
          :class="{ 'text-primary': sortBy === 'sales', 'text-gray-300': sortBy !== 'sales' }"></text>
      </view>
      <view class="filter-item flex-1 flex justify-center items-center"
        :class="{ 'text-primary': sortBy.startsWith('price') }" @tap="togglePriceSort">
        价格
        <text v-if="sortBy === 'price_asc'" class="fa fa-caret-up ml-1"></text>
        <text v-else-if="sortBy === 'price_desc'" class="fa fa-caret-down ml-1"></text>
        <text v-else class="fa fa-sort ml-1 text-gray-300"></text>
      </view>
      <view class="filter-item flex-1 flex justify-center items-center" @tap="showFilterPanel = true">
        筛选 <text class="fa fa-filter ml-1"></text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="product-list p-2.5">
      <view class="product-list-grid grid grid-cols-2 gap-2.5">
        <view v-for="(product, index) in filteredProducts" :key="index"
          class="product-list-item bg-white rounded-lg overflow-hidden shadow-sm" @tap="navigateToDetail(product.id)">
          <view class="product-list-image relative">
            <image :src="product.image" mode="aspectFill" class="w-full h-44 object-cover" />
            <view v-if="product.tag" class="product-tag absolute top-2 left-2 px-2 py-0.5 text-xs text-white rounded"
              :class="'tag-' + product.tagType">{{ product.tag }}</view>
          </view>
          <view class="product-list-info p-2.5">
            <view class="product-list-title text-sm mb-1.5 line-clamp-2 h-11">{{ product.title }}</view>
            <view class="product-list-price text-primary font-bold mb-1">¥{{ product.price }} <text
                class="original text-gray-400 text-xs line-through ml-1">¥{{ product.originalPrice }}</text></view>
            <view class="product-list-meta flex justify-between items-center text-xs text-gray-500">
              <view class="product-list-sales">已售{{ product.sales }}件</view>
              <view class="product-list-merchant truncate max-w-[50%]">{{ product.brand }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="isLoading" class="loading-more py-4 text-center text-gray-500 text-sm">
      <text class="fa fa-spinner fa-spin mr-2"></text> 加载中...
    </view>
    <view v-else-if="noMoreData" class="no-more-data py-4 text-center text-gray-400 text-sm">
      没有更多商品了
    </view>

    <!-- 筛选面板 -->
    <uni-popup ref="filterPopup" type="right">
      <view class="filter-panel bg-white h-full w-[80vw] p-4">
        <view class="filter-panel-header flex justify-between items-center mb-4">
          <view class="text-lg font-bold">筛选</view>
          <text class="fa fa-times p-2" @tap="showFilterPanel = false"></text>
        </view>

        <!-- 价格区间 -->
        <view class="filter-section mb-4">
          <view class="filter-title font-bold mb-2">价格区间</view>
          <view class="price-range flex items-center">
            <input type="number" v-model="priceRange.min" placeholder="最低价"
              class="flex-1 border border-gray-300 rounded p-2 text-sm" />
            <view class="mx-2 text-gray-400">-</view>
            <input type="number" v-model="priceRange.max" placeholder="最高价"
              class="flex-1 border border-gray-300 rounded p-2 text-sm" />
          </view>
        </view>

        <!-- 品牌筛选 -->
        <view class="filter-section mb-4">
          <view class="filter-title font-bold mb-2">品牌</view>
          <view class="brand-options flex flex-wrap">
            <view v-for="(brand, index) in brands" :key="index"
              :class="['brand-option mr-2 mb-2 px-3 py-1 border rounded-full text-sm',
          selectedBrands.includes(brand) ? 'border-primary text-primary bg-primary bg-opacity-5' : 'border-gray-300 text-gray-600']" @tap="toggleBrand(brand)">
              {{ brand }}
            </view>
          </view>
        </view>

        <!-- 其他筛选条件 -->
        <view class="filter-section mb-4">
          <view class="filter-title font-bold mb-2">商品类型</view>
          <view class="type-options flex flex-wrap">
            <view v-for="(type, index) in productTypes" :key="index"
              :class="['type-option mr-2 mb-2 px-3 py-1 border rounded-full text-sm',
          selectedTypes.includes(type) ? 'border-primary text-primary bg-primary bg-opacity-5' : 'border-gray-300 text-gray-600']" @tap="toggleType(type)">
              {{ type }}
            </view>
          </view>
        </view>

        <!-- 筛选按钮 -->
        <view class="filter-buttons flex mt-6">
          <button class="flex-1 py-2 border border-gray-300 rounded-full mr-2" @tap="resetFilters">重置</button>
          <button class="flex-1 py-2 bg-primary text-white rounded-full" @tap="applyFilters">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';

// 搜索关键词
const searchKeyword = ref('');

// 分类数据
const categories = ref([
  { id: 1, name: '全部' },
  { id: 2, name: '家居日用' },
  { id: 3, name: '数码配件' },
  { id: 4, name: '美妆个护' },
  { id: 5, name: '厨房用品' },
  { id: 6, name: '文具办公' },
  { id: 7, name: '箱包服饰' },
  { id: 8, name: '食品' }
]);

// 当前选中的分类
const currentCategory = ref(0);

// 排序方式
const sortBy = ref('default'); // default, sales, price_asc, price_desc

// 筛选面板显示状态
const showFilterPanel = ref(false);
const filterPopup = ref(null);

// 价格区间
const priceRange = ref({
  min: '',
  max: ''
});

// 品牌列表
const brands = ref(['名创优品', '无印良品', '宜家', '欧莱雅', '小米']);
const selectedBrands = ref([]);

// 商品类型
const productTypes = ref(['新品', '热卖', '促销', '限量版']);
const selectedTypes = ref([]);

// 加载状态
const isLoading = ref(false);
const noMoreData = ref(false);
const page = ref(1);
const pageSize = ref(10);

// 模拟商品数据
const products = ref([
  {
    id: 1,
    title: '便携式蓝牙音箱',
    price: 49.9,
    originalPrice: 99.9,
    sales: 2342,
    image: 'https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80',
    tag: '热卖',
    tagType: 'discount',
    brand: '名创优品',
    type: '热卖'
  },
  {
    id: 2,
    title: '时尚太阳镜',
    price: 39.9,
    originalPrice: 89.9,
    sales: 1568,
    image: 'https://images.unsplash.com/photo-1572635196237-14b3f281503f?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2080&q=80',
    tag: '新品',
    tagType: 'group',
    brand: '名创优品',
    type: '新品'
  },
  {
    id: 3,
    title: '便携式加湿器',
    price: 39.9,
    originalPrice: 69.9,
    sales: 986,
    image: 'https://images.unsplash.com/photo-1631729371254-42c2892f0e6e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2070&q=80',
    tag: '促销',
    tagType: 'bargain',
    brand: '无印良品',
    type: '促销'
  },
  {
    id: 4,
    title: '多功能笔记本',
    price: 15.9,
    originalPrice: 29.9,
    sales: 2156,
    image: 'https://images.unsplash.com/photo-1583394838336-acd977736f90?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2068&q=80',
    tag: '热卖',
    tagType: 'discount',
    brand: '名创优品',
    type: '热卖'
  },
  {
    id: 5,
    title: '简约智能手表',
    price: 89.9,
    originalPrice: 129.9,
    sales: 876,
    image: 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2099&q=80',
    tag: '限量版',
    tagType: 'flash',
    brand: '小米',
    type: '限量版'
  },
  {
    id: 6,
    title: '便携式化妆镜',
    price: 19.9,
    originalPrice: 39.9,
    sales: 1245,
    image: 'https://images.unsplash.com/photo-1560343090-f0409e92791a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1964&q=80',
    tag: '热卖',
    tagType: 'discount',
    brand: '欧莱雅',
    type: '热卖'
  },
  {
    id: 7,
    title: '多功能厨房剪刀',
    price: 12.9,
    originalPrice: 19.9,
    sales: 2567,
    image: 'https://images.unsplash.com/photo-1589782182703-2aaa69037b5b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2074&q=80',
    tag: '促销',
    tagType: 'bargain',
    brand: '宜家',
    type: '促销'
  },
  {
    id: 8,
    title: '便携式折叠水杯',
    price: 9.9,
    originalPrice: 19.9,
    sales: 3421,
    image: 'https://images.unsplash.com/photo-1602143407151-7111542de6e8?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=2073&q=80',
    tag: '热卖',
    tagType: 'discount',
    brand: '名创优品',
    type: '热卖'
  }
]);

// 筛选后的商品列表
const filteredProducts = computed(() => {
  let result = [...products.value];

  // 搜索关键词筛选
  if (searchKeyword.value) {
    result = result.filter(item =>
      item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }

  // 分类筛选
  if (currentCategory.value > 0) {
    // 实际项目中应该根据分类ID筛选
    // 这里简单模拟一下，奇数ID显示奇数商品，偶数ID显示偶数商品
    const categoryId = categories.value[currentCategory.value].id;
    if (categoryId % 2 === 0) {
      result = result.filter(item => item.id % 2 === 0);
    } else {
      result = result.filter(item => item.id % 2 !== 0);
    }
  }

  // 价格区间筛选
  if (priceRange.value.min) {
    result = result.filter(item => item.price >= Number(priceRange.value.min));
  }
  if (priceRange.value.max) {
    result = result.filter(item => item.price <= Number(priceRange.value.max));
  }

  // 品牌筛选
  if (selectedBrands.value.length > 0) {
    result = result.filter(item => selectedBrands.value.includes(item.brand));
  }

  // 商品类型筛选
  if (selectedTypes.value.length > 0) {
    result = result.filter(item => selectedTypes.value.includes(item.type));
  }

  // 排序
  switch (sortBy.value) {
    case 'sales':
      result.sort((a, b) => b.sales - a.sales);
      break;
    case 'price_asc':
      result.sort((a, b) => a.price - b.price);
      break;
    case 'price_desc':
      result.sort((a, b) => b.price - a.price);
      break;
    default:
      // 默认排序，这里简单按ID排序
      result.sort((a, b) => a.id - b.id);
  }

  return result;
});

// 监听筛选面板显示状态
watch(showFilterPanel, (newVal) => {
  if (newVal) {
    if (filterPopup.value) {
      filterPopup.value.open();
    }
  } else {
    if (filterPopup.value) {
      filterPopup.value.close();
    }
  }
});

// 组件挂载后初始化
onMounted(() => {
  // 确保filterPopup已经初始化
  setTimeout(() => {
    // 在uni-app中，ref会自动绑定到组件实例
    if (filterPopup.value) {
      console.log('筛选面板已初始化');
    }
  }, 100);
});

// 页面加载
onLoad((options) => {
  // 如果有分类参数，设置当前分类
  if (options.category) {
    const categoryIndex = categories.value.findIndex(item => item.id === Number(options.category));
    if (categoryIndex !== -1) {
      currentCategory.value = categoryIndex;
    }
  }

  // 如果有搜索关键词参数
  if (options.keyword) {
    searchKeyword.value = options.keyword;
  }

  // 加载商品数据
  loadProducts();
});

// 滚动到底部加载更多
onReachBottom(() => {
  if (!isLoading.value && !noMoreData.value) {
    loadProducts();
  }
});

// 加载商品数据
const loadProducts = () => {
  if (isLoading.value || noMoreData.value) return;

  isLoading.value = true;

  // 模拟网络请求
  setTimeout(() => {
    // 模拟没有更多数据
    if (page.value > 2) {
      noMoreData.value = true;
    } else {
      // 模拟加载更多数据
      const newProducts = products.value.map(item => ({
        ...item,
        id: item.id + page.value * 10
      }));
      products.value = [...products.value, ...newProducts];
      page.value++;
    }

    isLoading.value = false;
  }, 1000);
};

// 选择分类
const selectCategory = (index) => {
  currentCategory.value = index;
};

// 设置排序方式
const setSortBy = (type) => {
  sortBy.value = type;
};

// 切换价格排序
const togglePriceSort = () => {
  if (sortBy.value === 'price_asc') {
    sortBy.value = 'price_desc';
  } else {
    sortBy.value = 'price_asc';
  }
};

// 切换品牌选择
const toggleBrand = (brand) => {
  const index = selectedBrands.value.indexOf(brand);
  if (index === -1) {
    selectedBrands.value.push(brand);
  } else {
    selectedBrands.value.splice(index, 1);
  }
};

// 切换商品类型选择
const toggleType = (type) => {
  const index = selectedTypes.value.indexOf(type);
  if (index === -1) {
    selectedTypes.value.push(type);
  } else {
    selectedTypes.value.splice(index, 1);
  }
};

// 重置筛选条件
const resetFilters = () => {
  priceRange.value = { min: '', max: '' };
  selectedBrands.value = [];
  selectedTypes.value = [];
};

// 应用筛选条件
const applyFilters = () => {
  showFilterPanel.value = false;
  // 重新加载数据
  page.value = 1;
  noMoreData.value = false;
  // loadProducts();
};

// 跳转到商品详情
const navigateToDetail = (id) => {
  uni.navigateTo({
    url: `/pages/product/product_detail?id=${id}`
  });
};
</script>

<style lang="scss" scoped>
.product-list-page {
  min-height: 100vh;
  background-color: var(--bg-gray);
}

.search-bar {
  .search-input {
    background-color: #f5f5f5;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(228, 57, 60, 0.1);
    }
  }
}

.category-tabs {
  &::-webkit-scrollbar {
    display: none;
  }

  .category-tab {
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.95);
    }

    &.bg-primary {
      background-color: var(--primary-color);
    }
  }
}

.filter-bar {
  border-bottom: 1px solid var(--border-color);

  .filter-item {
    position: relative;
    font-size: 13px;
    transition: color 0.3s ease;

    &:active {
      opacity: 0.8;
    }

    &.text-primary {
      color: var(--primary-color);
    }
  }
}

.product-list-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.product-list-item {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease, box-shadow 0.2s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
}

.product-list-image {
  height: 180px;
  overflow: hidden;
  background-color: #f8f8f8;

  img {
    transition: transform 0.3s ease;
  }

  &:active img {
    transform: scale(1.05);
  }
}

.product-list-title {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 42px;
  color: var(--text-color);
}

.product-list-price {
  color: var(--primary-color);
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.original {
  color: var(--text-gray);
  font-size: 12px;
  text-decoration: line-through;
  margin-left: 5px;
  font-weight: normal;
}

.product-list-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--text-gray);
}

.product-list-sales {
  flex: 1;
}

.product-list-merchant {
  max-width: 50%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-tag {
  background-color: var(--primary-color);
  border-radius: 4px;
  padding: 2px 6px;
  font-weight: 500;
}

.tag-discount {
  background-color: #ff9800;
}

.tag-group {
  background-color: #7e57c2;
}

.tag-bargain {
  background-color: #26a69a;
}

.tag-flash {
  background-color: #f44336;
}

.filter-panel {
  box-shadow: -3px 0 10px rgba(0, 0, 0, 0.1);

  .filter-section {
    .filter-title {
      color: var(--text-color);
    }

    .brand-option,
    .type-option {
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
      }

      &.border-primary {
        border-color: var(--primary-color);
      }
    }
  }

  .filter-buttons {
    button {
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.98);
      }

      &.bg-primary {
        background-color: var(--primary-color);
      }
    }
  }
}

.loading-more,
.no-more-data {
  color: var(--text-gray);
}
</style>